from logging import getLogger

from django.db import models

from meercat.ui.django import connection
from meercat.ui.django.fields import MultiValueDictField



log = getLogger('meercat.ui.django.models')

class Resource(object):
    def __init__(self, identifier):
        self.identifier = identifier
        self.data = connection.getResource(identifier)
    
    @property
    def holdings(self):
        results = []
        if 'hodlings' in self.data:
            results.extend(self.data['holdings'])
        
        if 'instances' in self.data:
            for i in self.data['instances']:
                if 'holdings' in i:
                    results.extend(i['holdings'])
        
        return results
    
    def __getattr__(self, name):
        results = set()
        if name in self.data:
            results.update(self.data[name])
        
        if 'instances' in self.data:
            for i in self.data['instances']:
                if name in i:
                    results.update(i[name])
        
        return list(results)
            

class Search(models.Model):
    identifier = models.SlugField(primary_key=True)
    title = models.CharField(max_length=255, blank=False, null=False)
    description = models.TextField(blank=True, null=True)
    
    default_params = MultiValueDictField(editable=True, blank=True, null=True)
    forced_params = MultiValueDictField(editable=True, blank=True, null=True)
    
    def query(self, **params):
        qp = dict(self.default_params.iterlists())
        qp.update(params)
        qp.update(dict(self.forced_params.iterlists()))
        
        return connection.query(**qp)
        
    
    class Meta:
        db_table = 'meercat_search'
        verbose_name_plural = u'searches'
